package com.chijun.mform.show;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chijun.mform.FormBuilder;
import com.chijun.mform.R;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.recycler.BaseRecycler;
import com.example.ccj.b.c.recycler.SearchTextChangedLinsener;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 展示一个表单所有提交的数据
 *
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2025/1/3 3:41
 */
public class AllTheDataForAForm extends LinearLayout {

    BaseRecycler<ModeShowFullForm> formFullRecycler;
    List<ModeShowFullForm> showFullFormList;
    Map<Long,Map<String,String>> fieldDataMap;
    ShowData showDataLocal;
    TheLoadFormHasBeenFilledWithDataCallback callback;
    long formId;
    
    /**
     * 构造
     * @param context 上下文
     * @param showData 需要放入的数据
     */
    public AllTheDataForAForm(Context context,ShowData showData) {
        super(context);
        initView();
        setData(showData);
    }

    /**
     * 构造
     * @param context 上下文
     * @param formId 表单编号
     * @param callback 获取数据的回调
     */
    public AllTheDataForAForm(Context context,long formId,TheLoadFormHasBeenFilledWithDataCallback callback) {
        super(context);
        initView();
        setData(formId, callback);
    }

    public AllTheDataForAForm(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    /**
     * 传入编号从服务器获取
     * @param formId 数据id
     * @param callback 数据获取回调
     */
    public void setData (long formId,TheLoadFormHasBeenFilledWithDataCallback callback){
        this.formId = formId;
        this.callback = callback;
        showFullFormList = new ArrayList<>();
        fieldDataMap = new HashMap<>();
        //初始获取一次数据
        initialLoadOfServerData();
        //设置上拉加载下拉刷新功能
        setUpTheRefreshAndLoadingOfTheRecycler();
        //设置服务器数据的检索方式
        setUpTheServerDataLookupMechanism();
    }

    /**
     * 放入固定数据
     * 不具备下拉刷新下拉加载功能
     * @param showData 要放入的数据
     */
    public void setData(ShowData showData){
        this.showDataLocal = showData;
        formFullRecycler.setAdapter(showDataLocal.showFullFormList,new ApproximateInformationOnTheSubmittedFormDataAdapter(showDataLocal.showFullFormList,showDataLocal.fieldDataMap));
//        //加载本地数据
//        loadTheData(showData);
//        //设置本地数据的检索方式
        setUpALocalDataLookupMechanism();
    }

    /**
     * 初始化view
     */
    private void initView(){
        LinearLayout.inflate(getContext(), R.layout.view_all_the_data_a_form,this);
        formFullRecycler = findViewById(R.id.view_all_the_data_a_form_rec);
    }

    /**
     * 设置Recycler的刷新和加载数据机制
     */
    private void setUpTheRefreshAndLoadingOfTheRecycler(){
        //上拉加载
        formFullRecycler.setUpLoadMore(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadTheRemainingDataOnTheServer(showFullFormList.size());
            }
        });

        //下拉刷新
        formFullRecycler.setDownRefresh(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initialLoadOfServerData(); //从0开始重新拉取
            }
        });
    }

    /**
     * 设置本地数据检索方式
     */
    private void setUpALocalDataLookupMechanism(){
        formFullRecycler.showSearchControl(new SearchTextChangedLinsener() {
            @Override
            public void searchTextChange(String value) {
                retrieveLocalData(value);
            }

            @Override
            public void searchButtonClick(String value) {
                retrieveLocalData(value);
            }
        });
    }

    /**
     * 本地数据检索
     * 使用数据的toString()进行检索
     * @param value 检索文本
     */
    private void retrieveLocalData(String value){
        formFullRecycler.setControlState(BaseRecycler.DATA_STATE_LOAD);
        if (StringUtils.isEmpty(value)) {
            formFullRecycler.replaceData(showDataLocal.showFullFormList);
            formFullRecycler.setControlState(BaseRecycler.DATA_STATE_OK);
        } else {
            formFullRecycler.replaceData(new ArrayList<>());
            for (ModeShowFullForm modeFullForm : showDataLocal.showFullFormList) {
                if (modeFullForm.toString().contains(value)) {
                    formFullRecycler.addDataOnTail(modeFullForm);
                }
            }
            formFullRecycler.setControlState(BaseRecycler.DATA_STATE_OK);
        }
    }

    /**
     * 设置服务器数据检索方式
     */
    private void setUpTheServerDataLookupMechanism(){
        formFullRecycler.showSearchControl(new SearchTextChangedLinsener() {
            @Override
            public void searchTextChange(String value) {
                searchServerData(value);
            }

            @Override
            public void searchButtonClick(String value) {
                searchServerData(value);
            }
        });
    }

    /**
     * 查找服务器数据
     * @param value 要查找的文本
     */
    private void searchServerData(String value) {
        if (StringUtils.isEmpty(value)) {
            formFullRecycler.replaceData(showDataLocal.showFullFormList);
        } else {
            if (callback != null) {
                formFullRecycler.setControlState(BaseRecycler.DATA_STATE_LOAD);
                callback.onTheServerSearchesForFormDataReturns(formId,value, new WaitForTheCallbackToReturn() {
                    @Override
                    public void onResult(String resultData) {
                        ShowData sd = ShowData.parseTheData(resultData);
                        fieldDataMap.putAll(sd.fieldDataMap);
                        if (sd.showFullFormList != null) {
                            formFullRecycler.replaceData(sd.showFullFormList);
                        }
                        formFullRecycler.setControlState(BaseRecycler.DATA_STATE_OK);
                    }
                    @Override
                    public void onError(String error) {
                        formFullRecycler.setControlState(BaseRecycler.DATA_STATE_LOAD_ERROR);
                        formFullRecycler.setErrorData("获取数据失败！" + error);
                        ErrorDialog e = new ErrorDialog(getContext(),error);
                        e.show();
                    }
                });
            }
        }
    }

    /**
     * 初次获取服务器数据
     * 也可以说是刷新数据
     */
    private void initialLoadOfServerData(){
        //当前还需要获取数据时  条件1：当前数据是空的或者当前数据总量求余
        if (callback != null) {
            callback.onServerFormDataReturns(formId, 0, FormBuilder.THE_NUMBER_OF_FORMS_THAT_ARE_FETCHED_AT_A_TIME, new WaitForTheCallbackToReturn() {
                @Override
                public void onResult(String resultData) {
                    showDataLocal = ShowData.parseTheData(resultData);
                    showFullFormList.clear();
                    showFullFormList.addAll(showDataLocal.showFullFormList);
                    fieldDataMap.putAll(showDataLocal.fieldDataMap);
                    formFullRecycler.setAdapter(showFullFormList,new ApproximateInformationOnTheSubmittedFormDataAdapter(showFullFormList,fieldDataMap));
                    if (showFullFormList != null) {
                        //当返回的数据为空或者数量小于设置的预设获取数据时，设置为没有数据了; 否则加载回传的数据
                        if (showFullFormList.isEmpty() || showFullFormList.size() < FormBuilder.THE_NUMBER_OF_FORMS_THAT_ARE_FETCHED_AT_A_TIME) {
                            formFullRecycler.getRefreshLayout().finishRefreshWithNoMoreData();
                        } else {
                            formFullRecycler.getRefreshLayout().finishRefresh();
                        }
                    } else {
                        formFullRecycler.getRefreshLayout().finishRefresh();
                        LogUtils.e("请勿回传空值！！！");
                    }
                }
                @Override
                public void onError(String error) {
                    formFullRecycler.getRefreshLayout();
                    formFullRecycler.setControlState(BaseRecycler.DATA_STATE_LOAD_ERROR);
                    formFullRecycler.setErrorData("获取数据失败！" + error);
                    ErrorDialog e = new ErrorDialog(getContext(),error);
                    e.show();
                }
            });
        } else {
            //未传入获取数据的回调接口
            throw new NullPointerException("调用该方法需要传入(TheLoadFormHasBeenFilledWithDataCallback)回调");
        }
    }

    /**
     * 获取服务器剩余数据
     *
     * @param startIndex 起始位置 要从那个位置开始获取 一般为当前已获取的数据量
     */
    private void loadTheRemainingDataOnTheServer(int startIndex) {
        //加载剩余数据时检查显示的数据是否是检索数据，如果是替换为当前数据
        if (showFullFormList != formFullRecycler.getDefaultData()) {
            formFullRecycler.replaceData(showDataLocal.showFullFormList);
        }
        //当前还需要获取数据时  条件1：当前数据是空的或者当前数据总量求余
        if (callback != null) {
            callback.onServerFormDataReturns(formId, startIndex, FormBuilder.THE_NUMBER_OF_FORMS_THAT_ARE_FETCHED_AT_A_TIME, new WaitForTheCallbackToReturn() {
                @Override
                public void onResult(String resultData) {
                    if (resultData  != null) {
                        ShowData showDataLocal = ShowData.parseTheData(resultData);
                        loadTheData(showDataLocal); //加载数据
                    } else {
                        formFullRecycler.getRefreshLayout().finishLoadMore();
                        LogUtils.e("请勿回传空值！！！");
                    }
                }
                @Override
                public void onError(String error) {
                    formFullRecycler.getRefreshLayout().finishLoadMore();
                    formFullRecycler.setControlState(BaseRecycler.DATA_STATE_LOAD_ERROR);
                    formFullRecycler.setErrorData("获取数据失败！" + error);
                    ErrorDialog e = new ErrorDialog(getContext(),error);
                    e.show();
                }
            });
        } else {
            //未传入获取数据的回调接口
            throw new NullPointerException("调用该方法需要传入(TheLoadFormHasBeenFilledWithDataCallback)回调");
        }
    }

    private void loadTheData(ShowData showData) {
        showDataLocal.showFullFormList.addAll(showData.showFullFormList);
        if (showData.fieldDataMap != null) fieldDataMap.putAll(showData.fieldDataMap);
        formFullRecycler.addDatas(showData.showFullFormList);
        //当返回的数据为空或者数量小于设置的预设获取数据时，设置为没有数据了; 否则加载回传的数据
        if (showData.showFullFormList.isEmpty() || showData.showFullFormList .size() < FormBuilder.THE_NUMBER_OF_FORMS_THAT_ARE_FETCHED_AT_A_TIME) {
            formFullRecycler.getRefreshLayout().finishLoadMoreWithNoMoreData();
        } else {
            formFullRecycler.getRefreshLayout().finishLoadMore();
        }
    }
}
